package com.wwlwxg.spring_security.config;

import org.apache.catalina.authenticator.jaspic.PersistentProviderRegistrations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private UserDetailsService userDetailsService;

  @Autowired
  private DataSource dataSource;

  @Bean
  public PersistentTokenRepository persistentTokenRepository() {
    JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
//    jdbcTokenRepository.setCreateTableOnStartup(true);
    jdbcTokenRepository.setDataSource(dataSource);
    return jdbcTokenRepository;
  }


  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//    String password = passwordEncoder.encode("123");
//    auth.inMemoryAuthentication().withUser("lucy").password(password).roles("admin");

    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    // 配置退出程序
    http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();

    // 配置没有权限访问跳转自定义界面
    http.exceptionHandling().accessDeniedPage("/unauth.html");

    http.formLogin()  // 自定义自己编写的登录页面
            .loginPage("/login.html")  // 登录页面设置
            .loginProcessingUrl("/user/login")  // 登录页面路径
            .defaultSuccessUrl("/success.html").permitAll()  // 登录成功之后，跳转路径
            .and().authorizeRequests()
              .antMatchers("/", "/test/hello", "/user/login", "/get", "/test/**", "/acount").permitAll()  // 设置哪些路径可以直接访问，不需要认证
                // 1. hasAuthority
//              .antMatchers("/test/index").hasAuthority("admin")   // 当前登录用户，只有具有 admin 权限才可以访问这个路径
                // 2. hasAnyAuthority
//              .antMatchers("/test/index").hasAnyAuthority("admin,manager")
            // 3. hasRole ROLE_sale
            .antMatchers("/test/index").hasRole("sale")
            .anyRequest().authenticated()
            .and().rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(60).userDetailsService(userDetailsService)
            .and().csrf().disable();  // 关闭 csrf 防护
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}
